import * as types from '@/store/mutation-types';
// import i18n from 'vue-i18n';
import { login, regist } from '@/request/login';
import { set } from '@/common/utils';
import router from '@/router';
// import router from '@/router';
// import { remove } from 'lodash';

export default {
  async userLogin({ commit }, { username, password }) {
    //* 先判断
    const nameEle = /^[a-zA-Z0-9]{4,16}$/;
    const passwordEle = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
    if (!nameEle.test(username)) {
      commit(types.SHOW_ALERT, { message: 'login.error.name' });
    } else if (!passwordEle.test(password)) {
      commit(types.SHOW_ALERT, { message: 'login.error.password' });
    } else {
      // * 显示loading
      commit(types.SHOW_LOADING);

      try {
        // * 发送请求
        const result = await login({ username, password });
        // * localstorage中存住用户信息
        set('user', result);
        // * 在vuex中，存用户信息
        commit(types.SET_USER_INFO, { user: result });
        // console.log(result);
        // 拿到结果之后跳转
        if (result) {
          if (router.back(-1)) {
            router.back(-1);
          } else {
            router.push('/restaurant');
          }
        }
      } catch (error) {
        commit(types.SHOW_ALERT, { message: error.message });
      } finally {
        // * 最终移除loading
        commit(types.HIDE_LOADING);
      }
    }
  },

  //* userRegist
  async userRegist({ commit }, {
    username, password, confirmPassword, modal,
  }) {
    const nameEle = /^[a-zA-Z0-9]{4,16}$/;
    const passwordEle = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
    if (!nameEle.test(username)) {
      commit(types.SHOW_ALERT, { message: ('login.error.name') });
    } else if (!passwordEle.test(password)) {
      commit(types.SHOW_ALERT, { message: ('login.error.password') });
    } else if (confirmPassword !== password) {
      commit(types.SHOW_ALERT, { message: ('login.error.confirmPassword') });
    } else {
      // * 显示loading
      commit(types.SHOW_LOADING);
      try {
        await regist({ username, password });
        //* 显示alert成功执行state.alert.func
        commit(types.SHOW_ALERT, {
          message: '成功',
          func: () => {
            //* 关闭modal
            // console.log(modal);
            modal.hide('my-first-modal'); // 将modal从前面传过来
          },
        });
      } catch (error) {
        console.log(error);
        commit(types.SHOW_ALERT, { message: error.message });
      } finally {
        // * 最终移除loading
        commit(types.HIDE_LOADING);
      }
    }
  },

  async showRegist({ commit }) {
    commit(types.SHOW_REGIST);
  },
  async  hideRegist({ commit }) {
    commit(types.HIDE_REGIST);
  },

  userLogout({ commit }) { // 清除localStorage & vuex 里面的信息
    localStorage.removeItem('user');
    commit(types.CLEAR_USER_INFO);
  },
};
